import Vue from 'vue'
export const request = (url, params, method, loading, hideError) => {
	loading = loading || false
	if (loading === true) {
		uni.showLoading()
	} else {
		if (loading) {
			uni.showLoading({
				title: loading
			});
		}
	}

	let userToken = uni.getStorageSync("token")
	let lang = uni.getStorageSync("lang")
	lang = lang ? lang : 'zh'
	

	let header = {
		'lang': lang,
	}

	if (userToken) {
		header['token'] = userToken
	}

	return uni.request({
		url: url,
		method: method,
		dataType: 'json',
		header: header,
		data: params
	}).then(res => {

		if (loading != false) {
			uni.hideLoading()
		}
		let result = res
		if (result.statusCode !== 200) {
			throw {
				errMsg: '获取服务器数据失败',
				code: result.statusCode
			}
		}
		if (result.data.code === 401) {
			throw {
				errMsg: '未登录',
				code: result.data.code
			}
		}
		if (result.data.code !== 200) {
			throw {
				errMsg: result.data.msg
			}
		}
		return result.data
	}).catch(err => {
		if (loading != false) {
			uni.hideLoading()
		}
		if (err.code === 401) {
			uni.navigateTo({
				url: '/pages/common/login'
			})
		} else if (err.code === 403) {
			uni.showToast({
				title: err.errMsg,
				icon: 'none'
			})
			setTimeout(function() {
				uni.removeStorageSync('token')
				window.location.href = "#/pages/common/login"
			}, 500)
		} else {
			if (!hideError) {
				uni.showToast({
					title: err.errMsg,
					icon: 'none'
				})
			}
		}
		return err
	})
}

export const requestGet = (url, params, loading, hideError) => {
	return request(url, params, 'GET', loading, hideError)
}

export const requestPost = (url, params, loading, hideError) => {
	return request(url, params, 'POST', loading, hideError)
}

export const changeTitle = (lang) => {
	let pages = getCurrentPages()
	let currentPage = pages[pages.length - 1]
	let pageName = currentPage.$holder.navigationBarTitleText
	let $t = Vue.prototype._i18n
	uni.setNavigationBarTitle({
		title: $t['messages'][lang][pageName]
	})
}


export const getSystemLang = () => {
	// ar-US 阿拉伯
	// tr-US 土耳其
	// vi-US 越南
	// en-US 英语

	// zh-CN
	// en-US
	// ar-EG 阿拉伯
	// vi-VN 越南
	let lang = uni.getStorageSync('lang') || 'vie'

	if (lang) {
		return lang
	}
	let systemLanguage = uni.getSystemInfoSync().language.substr(0, 2)
	console.log('systemLanguage', systemLanguage)
	if (systemLanguage == 'ar') {
		lang = 'ar'
	} else if (systemLanguage == 'tr') {
		lang = 'tur'
	} else if (systemLanguage == 'vi') {
		lang = 'vie'
	} else if (systemLanguage == 'en') {
		lang = 'en'
	} else {
		lang = 'en'
	}

	uni.setStorageSync('lang', lang)
	return lang
}